<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Cadastro extends Controller_GradeHorariaFrontend{
    public $view;
    
    public function before(){
        parent::before();
    }
    public function action_index(){
        $this->view->js["1_cadastro"] = array(
                                    "type"=>"text/javascript",
                                    "src"=>DOC_ROOT."modules/grademagica/static/jscript/1_cadastro.js",
                                    );
        $this->view->css["1_cadastro"] = array(
                        "rel"=>"stylesheet",
                        "href"=>DOC_ROOT."modules/grademagica/static/css/1_cadastro.css",
                        "type"=>"text/css",
                        "media"=>"screen",
                        "charset"=>"utf-8",
                    );
        
        if(Model_User::logged_in(Kohana::$config->load("grademagica")->webuser_role_name)) {
            $user = Model_User::get_user();
            $this->view->body->content = Smarty_View::factory("1_register/my_data.tpl");		
            $this->view->body->content->user = $user;
            
            //carrega instituição
            $user_institutions=Model_Institution::get_user_institution($user->get_id());
            if($user_institutions){
                foreach($user_institutions as $institution){
                    
                }
                $this->view->body->content->institutions = Smarty_View::factory("2_insert_data/existant_institutions.tpl");
                $this->view->body->content->institution->institution_infos = new Model_Institution($user_institutions);
            }else{
                $this->view->body->content->institution_form_tpl = Smarty_View::factory("2_insert_data/institution_form.tpl")->render();
            }
        }else{
            $this->view->body->content = Smarty_View::factory("1_register/register.tpl");		
            $this->view->body->content->signin = Smarty_View::factory("1_register/signin.tpl");		
            $this->view->body->content->login = Smarty_View::factory("1_register/login.tpl");		
            if(isset($_GET["redirect"])){
                $this->view->body->content->signin->redirect = $_GET["redirect"];
                $this->view->body->content->login->redirect = $_GET["redirect"];
            }
            if(Arr::get(Kohana::modules(), "facebook")) {
                    $this->view->body->content->facebook = Smarty_View::factory("facebookLoginButton.tpl");
            }
        }
        $this->response->body($this->view);
    }
    public function action_login($redirect = '/',$template='auth/login.tpl') {        
        if (Model_User::login($_POST['email'], $_POST['password'])) {
                if (isset($_POST["redirect"]) && !empty($_POST["redirect"])) {
                        $redirect = $_POST["redirect"];
                } else {
                        $redirect = "/";
                }
                $this->request->redirect("/dados");
//                $this->request->redirect($redirect);
//                Request::current()->redirect('/');
        } else {
                $errors = array("login" => __("Invalid login"));
                $this->response->body(Json_View::factory(array("content" => $errors)));
        }
//        try {
//        } catch (Exception $e) {
//                $errors = array("_external" => array("Login" => $e->getMessage()));
//                $this->response->body(Json_View::factory(array("content" => $errors)));
//        }
    }
    public function action_logout() {
            Model_User::logout();
            Request::current()->redirect('/');
    }
    public function action_signin() {
        return $this->response->body(Json_View::factory(Model_Validate::validate_signin_fields($_POST)));;
                if(true !== ($return = Model_Validate::validate_signin_fields($_POST))){
                    return $this->response->body(Json_View::factory($return));;
                }else{
                    $user = Model_User::factory();
                    try {
                            if(Model_User::confirm_password($_POST['password'], $_POST['password_confirm'])) {
                                    if(Model_User::unique_email($_POST['email'])) {
                                            $user->set_name($_POST['name']);
                                            $user->set_email($_POST['email']);
                                            $user->set_password(Model_User::hash($_POST['password']));
                                            $user->save();
                                            $user->add_role('login');
                                            Request::current()->redirect("/dados");
                                    }
                            }
                    } catch (Validation_Exception $e) {
                            $this->response->body(Json_View::factory(array("content" => $e->errors())));
                    } catch (Exception $e) {
                            $errors = array("email" => $e->getMessage());
                            $this->response->body(Json_View::factory(array("content" => $errors)));
                    }
                }
	}
        public function action_search_countries(){
            if(isset($_GET['expression'])){
//                die("enc=".  htmlspecialchars_decode($_GET['expression'])." dec=". html_entity_decode($_GET['expression']));
//                die("enc=".utf8_encode($_GET['expression'])." dec=".  utf8_decode($_GET['expression']));
		$this->response->body(Json_View::factory(Model_Country::search_country(htmlspecialchars_decode($_GET['expression']))));
            }else{
		$this->response->body(Json_View::factory("\$_GET not set!"));
            }
	}
        public function action_search_states(){
            if(isset($_GET['expression'])){
		$this->response->body(Json_View::factory(Model_State::search_state(htmlspecialchars_decode($_GET['expression']))));
            }else{
		$this->response->body(Json_View::factory("\$_GET not set!"));
            }
	}
        public function action_search_cities(){
            if(isset($_GET['expression']) && isset($_GET['state_id'])){
		$this->response->body(Json_View::factory(Model_City::search_city(htmlspecialchars_decode($_GET['expression']), $_GET['state_id'])));
            }else{
		$this->response->body(Json_View::factory(array("GET values were not set!")));
            }
	}
        public function action_search_institutions(){
            if(isset($_GET['expression']) && isset($_GET['institution_city'])){
		$this->response->body(Json_View::factory(Model_Institution::search_institution(htmlspecialchars_decode($_GET['expression']), $_GET['institution_city'])));
            }else{
		$this->response->body(Json_View::factory(array("GET values were not set!")));
            }
	}
        public function action_search_classof(){
            if(isset($_GET['expression']) && isset($_GET['institution_id']) && isset($_GET['institution_city_id']) && isset($_GET['institution_start']) && isset($_GET['institution_end'])){
		$this->response->body(Json_View::factory(
                        Model_Classof::search_classof(
                                htmlspecialchars_decode($_GET['expression']), 
                                $_GET['institution_id'], 
                                htmlspecialchars_decode($_GET['institution_start']), 
                                htmlspecialchars_decode($_GET['institution_city_id']), 
                                htmlspecialchars_decode($_GET['institution_end']))
                        ));
            }else{
		$this->response->body(Json_View::factory(array("GET values were not set!")));
            }
	}
        public function action_recuperar_senha(){
            $user = new Model_User($_POST['email']);
            $new_pass="";
            
            if(!$user) 
                return "bad_email";
            else{
                $new_pass = md5(date("d M YMM HY:is:si"));
                $user->set_password(Model_User::hash($new_pass));
                $user->save();
                if(Email::send_password_recovery($_POST["email"],$new_pass)){
                    return "new password sent";
                }else{
                    return "error sending";
                }
                
            }
        }
        
        public function action_redefinir_senha(){
            
        }
}